package com.ankicoo.file.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.OSSObject;
import com.ankicoo.file.config.OssConnect;
import com.ankicoo.file.service.OssFileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * Description:
 *
 * @author : QCYANG
 * @date : 2021/7/15 18:03
 */
@Service
public class OssFileServiceImpl implements OssFileService {

    @Autowired
    private OssConnect ossConnect;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void upload(@NonNull MultipartFile file){
        String fileName = file.getOriginalFilename();
        InputStream input = null;
        try {
            input = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        upload(fileName, input);
    }

    @Override
    public void upload(String fileName, InputStream input){
        OSS oss = ossConnect.getOssClient();
        oss.putObject(ossConnect.bucketName, fileName, input);
        logger.info(this.getClass()+"upload@ 文件上传成功 目标bucket：【"+ossConnect.bucketName+"】 && 文件名：【"+fileName+" 】");
        oss.shutdown();
    }

    @Override
    public InputStream openInputStream(String filePath){
        OSSObject ossObject = download(filePath);
        return ossObject.getObjectContent();
    }

    @Override
    public OSSObject download( String fileName){
        OSS oss = ossConnect.getOssClient();
        return oss.getObject(ossConnect.bucketName, fileName);
    }

    @Override
    public void delete(String fileName){
        OSS oss = ossConnect.getOssClient();
        oss.deleteObject(ossConnect.bucketName, fileName);
    }
}
